clearvars
close all

% path of the file containing the wave time series. The file contains no header, 
% the first column is the time (in seconds) and the second column is the wave
% elevation (in meters). The file is comma-separated
input_path = 'wave.txt';

% read the file
T = dlmread(input_path);

t = T(:,1); % time
w = T(:,2); % wave elevation

% create a vector containing the frequencies for the fft components from the time vector
f = 1/(t(2)-t(1))*linspace(0,1,length(t));

% generate fft components from the wave elevation
Y = fft(w);

% generate the amplitudes and phases of the wave components as they will be read by Ashes
Amps = 4*abs(Y)/length(Y);
Phases = -(360*arg(Y)/(2*pi)+90);

% we don't want all the components: high and low frequency are too small 
% (and too many components will slow down the simulation)
% therefore we set a cut-in and cut-out frequencies
cutin = 0.05;
cutout = 0.5;

% find the components within the cut-in and cut-out frequencies
I = find((f>cutin)&(f<cutout));

% keep the amplitudes and phases of the wave components that are within the cut-in
% and cut-out frequencies
f2 = f(I);
Amps2 = Amps(I);
Phases2 = Phases(I);

% create the file that will contain the wave spectrum, and write the header
fID = fopen('spectrum.txt','w');

fprintf(fID, 'Irregular waves components\n');
fprintf(fID, '# Period (s)\tHeight (m)\tPhase angle (deg)\tDir (deg)\n');

fclose(fID);

% write the wave components in the file. See https://www.simis.io/docs/file-formats-wave-spectrum-file
% for info on the format
dlmwrite('spectrum.txt',[1./f2',Amps2,Phases2,zeros(size(f2'))],'\t','-append');


